/*
 * LoginService.java
 * Copyright (c) 2014, 2019, Kiri. 
 * All rights reserved.
 */
package com.onesalt.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onesalt.domain.UserLogin;
import com.onesalt.utils.EncryptUtil;

/**
 * @author kiri
 * @date 2015年4月9日
 * @version 1.0
 */
@Service
@Transactional
public class LoginService extends AbstractService {
	
	private final UserRepository userRepository;
	
	private final UserLoginRepository userLoginRepository;

	@Autowired
	public LoginService(UserRepository userRepository, UserLoginRepository userLoginRepository) {
		this.userRepository = userRepository;
		this.userLoginRepository = userLoginRepository;
	}

	public UserRepository getUserRepository() {
		return userRepository;
	}

	public UserLoginRepository getUserLoginRepository() {
		return userLoginRepository;
	}
	
	public UserLogin login(long userId, int loginType, String client, String version, String deviceId, Date lastOpenAppTime) {
		UserLogin ul = getUserLoginRepository().findByUserIdAndDeviceId(userId, deviceId);
		if (ul == null) {
			ul = new UserLogin();
			ul.setCreateTime(new Date());
			ul.setUserId(userId);
			ul.setDeviceId(deviceId);
		}
		ul.setLoginTime(new Date());
		ul.setLoginType(loginType);
		ul.setModifyTime(ul.getLoginTime());
		ul.setToken(EncryptUtil.encodeUserId(userId));
		ul.setClient(client);
		ul.setVersion(version);
		ul.setLastOpenAppTime(lastOpenAppTime);
		return getUserLoginRepository().save(ul);
	}
}
